package TCP和UDP;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoServer{
    private ServerSocket serverSocket = null;
    public TcpEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动！");
        while(true) {
            Socket clientSocket = serverSocket.accept();
            Thread t = new Thread(() -> {
                processConnection(clientSocket);
            });
            t.start();
        }
    }

    private void processConnection(Socket clientSocket){
        //提醒客户端上线
        System.out.printf("[%s:%d]客户端上线！\n",clientSocket.getInetAddress(),clientSocket.getPort());
        try (InputStream inputStream = clientSocket.getInputStream();
             OutputStream outputStream = clientSocket.getOutputStream()){
            while(true) {
                Scanner scanner = new Scanner(inputStream);
                if(!scanner.hasNext()) {
                    System.out.printf("[%s:%d]客户端下线！\n",clientSocket.getInetAddress(),clientSocket.getPort());
                    break;
                }
                //1.读取请求并解析，next的规则是读到”空白符“就返回
                String request = scanner.next();
                //2.根据请求计算响应
                String response = process(request);
                //3.把响应写回客户端
                //可以将String转化成byte数组，然后写回客户端
                //也可以通过PrintWriter进行包装，然后通过调用println方法写回客户端
                PrintWriter printWriter = new PrintWriter(outputStream);
                //这里选择使用println方法是为了方便后续客户端这边能够通过scanner.next()来读取数据
                printWriter.println(response);

                //此外还需要记得有一个操作就是刷新内存否则数据还是在内存中，没有写入到网卡中去
                printWriter.flush();

                System.out.printf("[%s:%d]:request = %s,response = %s\n",clientSocket.getInetAddress(),clientSocket.getPort(),request,response);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                clientSocket.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    //这里响应就是请求
    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer tcpEchoServer = new TcpEchoServer(9090);
        tcpEchoServer.start();
    }
}
